/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.coder.struts.wrapper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cn.coder.struts.util.Streams;

/**
 * 解析Multipart
 * 
 */
public final class MultipartStream {

	// ----------------------------------------------------- Manifest constants

	/**
	 * The Carriage Return ASCII character value.
	 */
	public static final byte CR = 0x0D;

	/**
	 * The Line Feed ASCII character value.
	 */
	public static final byte LF = 0x0A;

	/**
	 * The dash (-) ASCII character value.
	 */
	public static final byte DASH = 0x2D;

	/**
	 * A byte sequence that marks the end of <code>header-part</code>
	 * (<code>CRLFCRLF</code>).
	 */
	protected static final byte[] HEADER_SEPARATOR = { CR, LF, CR, LF };

	/**
	 * A byte sequence that that follows a delimiter that will be followed by an
	 * encapsulation (<code>CRLF</code>).
	 */
	protected static final byte[] FIELD_SEPARATOR = { CR, LF };

	/**
	 * A byte sequence that that follows a delimiter of the last encapsulation
	 * in the stream (<code>--</code>).
	 */
	protected static final byte[] STREAM_TERMINATOR = { DASH, DASH };

	/**
	 * A byte sequence that precedes a boundary (<code>CRLF--</code>).
	 */
	protected static final byte[] BOUNDARY_PREFIX = { CR, LF, DASH, DASH };

	// ----------------------------------------------------------- Data members

	/**
	 * The input stream from which data is read.
	 */
	private final InputStream input;

	/**
	 * The length of the boundary token plus the leading <code>CRLF--</code>.
	 */
	private int boundaryLength;

	/**
	 * The amount of data, in bytes, that must be kept in the buffer in order to
	 * detect delimiters reliably.
	 */
	private final int keepRegion;

	/**
	 * The byte sequence that partitions the stream.
	 */
	private final byte[] boundary;

	/**
	 * The table for Knuth-Morris-Pratt search algorithm.
	 */
	private int[] boundaryTable;

	/**
	 * The length of the buffer used for processing the request.
	 */
	private final int bufSize;

	/**
	 * The buffer used for processing the request.
	 */
	private final byte[] buffer;

	/**
	 * The index of first valid character in the buffer. <br>
	 * 0 <= head < bufSize
	 */
	private int head;

	/**
	 * The index of last valid character in the buffer + 1. <br>
	 * 0 <= tail <= bufSize
	 */
	private int tail;

	/**
	 * The content encoding to use when reading headers.
	 */
	private String headerEncoding;

	// ----------------------------------------------------------- Constructors

	/**
	 * <p>
	 * Constructs a <code>MultipartStream</code> with a custom size buffer.
	 *
	 * <p>
	 * Note that the buffer must be at least big enough to contain the boundary
	 * string, plus 4 characters for CR/LF and double dash, plus at least one
	 * byte of data. Too small a buffer size setting will degrade performance.
	 *
	 * @param input
	 *            The <code>InputStream</code> to serve as a data source.
	 * @param boundary
	 *            The token used for dividing the stream into
	 *            <code>encapsulations</code>.
	 *
	 * @since 1.3.1
	 */
	public MultipartStream(InputStream input, byte[] boundary) {

		// We prepend CR/LF to the boundary to chop trailing CR/LF from
		// body-data tokens.
		this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length;

		this.input = input;
		this.bufSize = Math.max(4096, this.boundaryLength * 2);
		this.buffer = new byte[this.bufSize];

		this.boundary = new byte[this.boundaryLength];
		this.boundaryTable = new int[this.boundaryLength + 1];
		this.keepRegion = this.boundary.length;

		System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0, BOUNDARY_PREFIX.length);
		System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length);
		computeBoundaryTable();

		head = 0;
		tail = 0;
	}

	/**
	 * Reads a byte from the <code>buffer</code>, and refills it as necessary.
	 *
	 * @return The next byte from the input stream.
	 *
	 * @throws IOException
	 *             if there is no more data available.
	 */
	private byte readByte() throws IOException {
		// Buffer depleted ?
		if (head == tail) {
			head = 0;
			// Refill.
			tail = input.read(buffer, head, bufSize);
			if (tail == -1) {
				// No more data available.
				throw new IOException("No more data is available");
			}
		}
		return buffer[head++];
	}

	/**
	 * Skips a <code>boundary</code> token, and checks whether more
	 * <code>encapsulations</code> are contained in the stream.
	 *
	 * @return <code>true</code> if there are more encapsulations in this
	 *         stream; <code>false</code> otherwise.
	 *
	 * @throws IOException
	 *             if the bytes read from the stream exceeded the size limits
	 */
	public boolean readBoundary() throws IOException {
		byte[] marker = new byte[2];
		boolean nextChunk = false;

		head += boundaryLength;
		try {
			marker[0] = readByte();
			if (marker[0] == LF) {
				// Work around IE5 Mac bug with input type=image.
				// Because the boundary delimiter, not including the trailing
				// CRLF, must not appear within any file (RFC 2046, section
				// 5.1.1), we know the missing CR is due to a buggy browser
				// rather than a file containing something similar to a
				// boundary.
				return true;
			}

			marker[1] = readByte();
			if (arrayequals(marker, STREAM_TERMINATOR, 2)) {
				nextChunk = false;
			} else if (arrayequals(marker, FIELD_SEPARATOR, 2)) {
				nextChunk = true;
			} else {
				throw new IOException("Unexpected characters follow a boundary");
			}
		} catch (IOException e) {
			throw e;
		}
		return nextChunk;
	}

	/**
	 * Compute the table used for Knuth-Morris-Pratt search algorithm.
	 */
	private void computeBoundaryTable() {
		int position = 2;
		int candidate = 0;

		boundaryTable[0] = -1;
		boundaryTable[1] = 0;

		while (position <= boundaryLength) {
			if (boundary[position - 1] == boundary[candidate]) {
				boundaryTable[position] = candidate + 1;
				candidate++;
				position++;
			} else if (candidate > 0) {
				candidate = boundaryTable[candidate];
			} else {
				boundaryTable[position] = 0;
				position++;
			}
		}
	}

	public String readHeaders() throws IOException {
		int i = 0;
		byte b;
		// to support multi-byte characters
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		while (i < HEADER_SEPARATOR.length) {
			try {
				b = readByte();
			} catch (IOException e) {
				throw e;
			}
			if (b == HEADER_SEPARATOR[i]) {
				i++;
			} else {
				i = 0;
			}
			baos.write(b);
		}

		String headers = null;
		if (headerEncoding != null) {
			try {
				headers = baos.toString(headerEncoding);
			} catch (IOException e) {
				// Fall back to platform default if specified encoding is not
				// supported.
				headers = baos.toString();
			}
		} else {
			headers = baos.toString();
		}

		return headers;
	}

	public InputStream getInputStream() {
		return new ItemInputStream();
	}

	/**
	 * <p>
	 * Reads <code>body-data</code> from the current <code>encapsulation</code>
	 * and discards it.
	 *
	 * <p>
	 * Use this method to skip encapsulations you don't need or don't
	 * understand.
	 *
	 * @return The amount of data discarded.
	 *
	 * @throws IOException
	 *             if an i/o error occurs.
	 */
	private int discardBodyData() throws IOException {
		return (int) Streams.copy(new ItemInputStream(), null, false);
	}

	/**
	 * Finds the beginning of the first <code>encapsulation</code>.
	 *
	 * @return <code>true</code> if an <code>encapsulation</code> was found in
	 *         the stream.
	 *
	 */
	public boolean skipPreamble() {
		// First delimiter may be not preceeded with a CRLF.
		System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2);
		boundaryLength = boundary.length - 2;
		computeBoundaryTable();
		try {
			// Discard all data up to the delimiter.
			discardBodyData();

			// Read boundary - if succeeded, the stream contains an
			// encapsulation.
			return readBoundary();
		} catch (IOException e) {
			return false;
		} finally {
			// Restore delimiter.
			System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2);
			boundaryLength = boundary.length;
			boundary[0] = CR;
			boundary[1] = LF;
			computeBoundaryTable();
		}
	}

	/**
	 * Compares <code>count</code> first bytes in the arrays <code>a</code> and
	 * <code>b</code>.
	 *
	 * @param a
	 *            The first array to compare.
	 * @param b
	 *            The second array to compare.
	 * @param count
	 *            How many bytes should be compared.
	 *
	 * @return <code>true</code> if <code>count</code> first bytes in arrays
	 *         <code>a</code> and <code>b</code> are equal.
	 */
	private static boolean arrayequals(byte[] a, byte[] b, int count) {
		for (int i = 0; i < count; i++) {
			if (a[i] != b[i]) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Searches for a byte of specified value in the <code>buffer</code>,
	 * starting at the specified <code>position</code>.
	 *
	 * @param value
	 *            The value to find.
	 * @param pos
	 *            The starting position for searching.
	 *
	 * @return The position of byte found, counting from beginning of the
	 *         <code>buffer</code>, or <code>-1</code> if not found.
	 */
	protected int findByte(byte value, int pos) {
		for (int i = pos; i < tail; i++) {
			if (buffer[i] == value) {
				return i;
			}
		}

		return -1;
	}

	/**
	 * Searches for the <code>boundary</code> in the <code>buffer</code> region
	 * delimited by <code>head</code> and <code>tail</code>.
	 *
	 * @return The position of the boundary found, counting from the beginning
	 *         of the <code>buffer</code>, or <code>-1</code> if not found.
	 */
	private int findSeparator() {

		int bufferPos = this.head;
		int tablePos = 0;

		while (bufferPos < this.tail) {
			while (tablePos >= 0 && buffer[bufferPos] != boundary[tablePos]) {
				tablePos = boundaryTable[tablePos];
			}
			bufferPos++;
			tablePos++;
			if (tablePos == boundaryLength) {
				return bufferPos - boundaryLength;
			}
		}
		return -1;
	}

	/**
	 * An {@link InputStream} for reading an items contents.
	 */
	private final class ItemInputStream extends InputStream {

		/**
		 * The number of bytes, which must be hold, because they might be a part
		 * of the boundary.
		 */
		private int pad;

		/**
		 * The current offset in the buffer.
		 */
		private int pos;

		/**
		 * Whether the stream is already closed.
		 */
		private boolean closed;

		/**
		 * Creates a new instance.
		 */
		ItemInputStream() {
			findSeparator();
		}

		/**
		 * Called for finding the separator.
		 */
		private void findSeparator() {
			pos = MultipartStream.this.findSeparator();
			if (pos == -1) {
				if (tail - head > keepRegion) {
					pad = keepRegion;
				} else {
					pad = tail - head;
				}
			}
		}

		/**
		 * Returns the number of bytes, which are currently available, without
		 * blocking.
		 *
		 * @throws IOException
		 *             An I/O error occurs.
		 * @return Number of bytes in the buffer.
		 */
		@Override
		public int available() throws IOException {
			if (pos == -1) {
				return tail - head - pad;
			}
			return pos - head;
		}

		/**
		 * Offset when converting negative bytes to integers.
		 */
		private static final int BYTE_POSITIVE_OFFSET = 256;

		/**
		 * Returns the next byte in the stream.
		 *
		 * @return The next byte in the stream, as a non-negative integer, or -1
		 *         for EOF.
		 * @throws IOException
		 *             An I/O error occurred.
		 */
		@Override
		public int read() throws IOException {
			if (closed) {
				throw new IOException("Stream has been closed");
			}
			if (available() == 0 && makeAvailable() == 0) {
				return -1;
			}
			// ++total;
			int b = buffer[head++];
			if (b >= 0) {
				return b;
			}
			return b + BYTE_POSITIVE_OFFSET;
		}

		/**
		 * Reads bytes into the given buffer.
		 *
		 * @param b
		 *            The destination buffer, where to write to.
		 * @param off
		 *            Offset of the first byte in the buffer.
		 * @param len
		 *            Maximum number of bytes to read.
		 * @return Number of bytes, which have been actually read, or -1 for
		 *         EOF.
		 * @throws IOException
		 *             An I/O error occurred.
		 */
		@Override
		public int read(byte[] b, int off, int len) throws IOException {
			if (closed) {
				throw new IOException("Stream has been closed");
			}
			if (len == 0) {
				return 0;
			}
			int res = available();
			if (res == 0) {
				res = makeAvailable();
				if (res == 0) {
					return -1;
				}
			}
			res = Math.min(res, len);
			System.arraycopy(buffer, head, b, off, res);
			head += res;
			// total += res;
			return res;
		}

		/**
		 * Closes the input stream.
		 *
		 * @throws IOException
		 *             An I/O error occurred.
		 */
		@Override
		public void close() throws IOException {
			close(false);
		}

		/**
		 * Closes the input stream.
		 *
		 * @param pCloseUnderlying
		 *            Whether to close the underlying stream (hard close)
		 * @throws IOException
		 *             An I/O error occurred.
		 */
		public void close(boolean pCloseUnderlying) throws IOException {
			if (closed) {
				return;
			}
			if (pCloseUnderlying) {
				closed = true;
				input.close();
			} else {
				for (;;) {
					int av = available();
					if (av == 0) {
						av = makeAvailable();
						if (av == 0) {
							break;
						}
					}
					skip(av);
				}
			}
			closed = true;
		}

		/**
		 * Skips the given number of bytes.
		 *
		 * @param bytes
		 *            Number of bytes to skip.
		 * @return The number of bytes, which have actually been skipped.
		 * @throws IOException
		 *             An I/O error occurred.
		 */
		@Override
		public long skip(long bytes) throws IOException {
			if (closed) {
				throw new IOException("Stream has been closed");
			}
			int av = available();
			if (av == 0) {
				av = makeAvailable();
				if (av == 0) {
					return 0;
				}
			}
			long res = Math.min(av, bytes);
			head += res;
			return res;
		}

		/**
		 * Attempts to read more data.
		 *
		 * @return Number of available bytes
		 * @throws IOException
		 *             An I/O error occurred.
		 */
		private int makeAvailable() throws IOException {
			if (pos != -1) {
				return 0;
			}

			// Move the data to the beginning of the buffer.
			// total += tail - head - pad;
			System.arraycopy(buffer, tail - pad, buffer, 0, pad);

			// Refill buffer with new data.
			head = 0;
			tail = pad;

			for (;;) {
				int bytesRead = input.read(buffer, tail, bufSize - tail);
				if (bytesRead == -1) {
					// The last pad amount is left in the buffer.
					// Boundary can't be in there so signal an error
					// condition.
					throw new IOException("Stream ended unexpectedly");
				}
				tail += bytesRead;

				findSeparator();
				int av = available();

				if (av > 0 || pos != -1) {
					return av;
				}
			}
		}
	}

}
